package com.ruoyi.web.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysUploadFile;
import com.ruoyi.system.domain.UploadFileType;
import com.ruoyi.system.service.ISysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * 附件信息Controller
 *
 * @author cqust_icc
 * @date 2022-04-16
 */
@RestController
@RequestMapping("/system/file")
public class SysFileController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);
    @Autowired
    private ISysFileService sysFileService;

    /**
     * 查询附件信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysUploadFile sysUploadFile) {
        startPage();
        List<SysUploadFile> list = sysFileService.selectSysFileList(sysUploadFile);
        return getDataTable(list);
    }
    /**
     * 获取附件信息详细信息
     */
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@PathVariable("fileId") Long fileId) {
        return AjaxResult.success(sysFileService.selectSysFileByFileId(fileId).getResult());
    }
    /**
     * 上传文件
     */
    @PostMapping("/latex")
    public AjaxResult latex(@RequestParam("file") MultipartFile file, String result) throws Exception {
        return AjaxResult.success("上传成功", sysFileService.SavaLatexFileToLocalStorage(result,  file));
    }

    /**
     * 导出附件信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:export')")
    @Log(title = "附件信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUploadFile sysUploadFile) {
        List<SysUploadFile> list = sysFileService.selectSysFileList(sysUploadFile);
        ExcelUtil<SysUploadFile> util = new ExcelUtil<>(SysUploadFile.class);
        util.exportExcel(response, list, "附件信息数据");
    }



    /**
     * 新增附件信息
     */
    @Log(title = "附件信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysUploadFile sysUploadFile) {
        return toAjax(sysFileService.insertSysFile(sysUploadFile));
    }

    /**
     * 修改附件信息
     */
    @Log(title = "附件信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysUploadFile sysUploadFile) {
        return toAjax(sysFileService.updateSysFile(sysUploadFile));
    }




    /**
     * 上传文件
     */
    @PostMapping("/banner_file")
    public AjaxResult bannerFile(@RequestParam("file") MultipartFile file, Long RelationId) throws Exception {
        return AjaxResult.success("上传成功", sysFileService.SavaFileToLocalStorage(1999L, RelationId, UploadFileType.BANNER, file));
    }

    @PostMapping("/marks_file")
    public AjaxResult marksFile(@RequestParam("file") MultipartFile file, @RequestParam("marksId") Long RelationId, @RequestParam("fileType") String fileType) throws Exception {

        if (Objects.equals(UploadFileType.MARKS_MODEL, fileType) || Objects.equals(UploadFileType.MARKS_PICTURE, fileType)) {
            sysFileService.deleteSysFileByMarks(RelationId,fileType);

            Long UserID = SecurityUtils.getLoginUser().getUser().getUserId();
            return AjaxResult.success("上传成功", sysFileService.SavaFileToLocalStorage(UserID, RelationId, fileType, file));
        } else if (Objects.equals(UploadFileType.MARKS_BANNER, fileType)) {
            Long UserID = SecurityUtils.getLoginUser().getUser().getUserId();
            return AjaxResult.success("上传成功", sysFileService.SavaFileToLocalStorage(UserID, RelationId, fileType, file));
        } else {
            return AjaxResult.error("请检查fileType");
        }

    }

    /**
     * 显示图片
     */
    @GetMapping("/showPic")
    public void showPhotos(@RequestParam("path") Long fileID, HttpServletResponse response) {

        try {
            SysUploadFile sysUploadFile = sysFileService.selectSysFileByFileId(fileID);
            if (sysUploadFile != null) {
                // 本地资源路径
                String localPath = RuoYiConfig.getProfile();
                // 数据库资源地址
                String downloadPath = localPath + StringUtils.substringAfter(sysUploadFile.getFilePath(), Constants.RESOURCE_PREFIX);

                response.setCharacterEncoding("utf-8");
                response.setContentType("image/jpeg");
                FileUtils.writeBytes(downloadPath, response.getOutputStream());
            } else {
                response.getWriter().write("showPic error ！");
            }
        } catch (Exception e) {
            log.error("图片加载失败", e);
        }
    }

    /**
     * 下载文件
     */
    @GetMapping("/downloadFile")
    public void download(@RequestParam("path") Long fileID, HttpServletResponse response, HttpServletRequest request) {

        try {
            SysUploadFile sysUploadFile = sysFileService.selectSysFileByFileId(fileID);
            if (sysUploadFile != null) {
                // 本地资源路径
                String localPath = RuoYiConfig.getProfile();
                // 数据库资源地址
                String downloadPath = localPath + StringUtils.substringAfter(sysUploadFile.getFilePath(), Constants.RESOURCE_PREFIX);

                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition",
                        "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, sysUploadFile.getFileName()));
                FileUtils.writeBytes(downloadPath, response.getOutputStream());
            } else {
                response.getWriter().write("download error ！");
            }
        } catch (Exception e) {
            log.error("图片加载失败", e);
        }
    }

    /**
     * 删除附件信息
     */
    @Log(title = "附件信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{fileIds}")
    public AjaxResult remove(@PathVariable Long[] fileIds) {
        return toAjax(sysFileService.deleteSysFileByFileIds(fileIds));
    }
}
